
package com.fatcat.easybuy.controller;

import com.fatcat.easybuy.annotaion.CheckPermission;
import com.fatcat.easybuy.pojo.EasyBuyOrder;
import com.fatcat.easybuy.pojo.EasyBuyOrderDetail;
import com.fatcat.easybuy.service.EasyBuyOrderDetailService;
import com.fatcat.easybuy.service.EasyBuyOrderService;
import com.fatcat.easybuy.util.ResponseResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/order")
public class EasyBuyOrderController {
    @Autowired
    private EasyBuyOrderService easyBuyOrderService;
    @Autowired
    private EasyBuyOrderDetailService easyBuyOrderDetailService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    // 订单过期键前缀
    private static final String ORDER_EXPIRE_KEY_PREFIX = "order:";

    /**
     * 创建订单接口
     */
    @PostMapping("/createOrder")
    @CheckPermission({"0", "1"})
    public ResponseResult createOrder(
            @RequestBody Map<Long, Integer> orderList,
            @RequestAttribute("userId") Long userId,
            @RequestParam("addressId") Integer addressId) {
        //保存订单到数据库（状态为“未付款”：status=1）
        if (!easyBuyOrderService.addOrder(orderList, userId, addressId)) {
            return ResponseResult.error("订单创建失败");
        }

        return ResponseResult.success().add("msg", "订单创建成功");
    }

    //全部订单
    @GetMapping("/getAllOrder")
    @CheckPermission({"0", "1"})
    public ResponseResult getAllOrder(@RequestParam Map<String, Object> params) {

        //查询订单
        PageInfo<EasyBuyOrder> pageInfo = easyBuyOrderService.selectAllOrder(params);

        //查询订单明细
        for (EasyBuyOrder easyBuyOrder : pageInfo.getList()) {

            String redisKey = ORDER_EXPIRE_KEY_PREFIX + easyBuyOrder.getId();
            String value = redisTemplate.opsForValue().get(redisKey);
            //未支付且 Redis 中不存在订单过期键，将订单状态设置为已关闭
            if (easyBuyOrder.getStatus() == 1 && value == null) {
                easyBuyOrder.setStatus(3);
                //更新订单状态
                easyBuyOrderService.closeOrder(easyBuyOrder.getSerialNumber());
            }
            easyBuyOrder.setEasyBuyOrderDetails(easyBuyOrderDetailService.getOrderDetailByOrderId(easyBuyOrder.getId()));
        }

        return ResponseResult.success().add("pageInfo", pageInfo);
    }

    //关闭订单
    @GetMapping("/closeOrder/{serialNumber}")
    @CheckPermission({"0", "1"})
    public ResponseResult closeOrder(@PathVariable String serialNumber) {
        EasyBuyOrder easyBuyOrder = easyBuyOrderService.getOrderBySerialNumber(serialNumber);
        //修改订单状态
        if (!easyBuyOrderService.closeOrder(serialNumber)) {
            return ResponseResult.error("关闭订单失败");
        }
        // 删除 Redis 中的订单过期键
        String redisKey = ORDER_EXPIRE_KEY_PREFIX + easyBuyOrder.getId().toString();
        redisTemplate.delete(redisKey);
        return ResponseResult.success("关闭订单成功");
    }

    //根据订单id删除订单
    @DeleteMapping("/deleteOrder/{orderId}")
    @CheckPermission({"0", "1"})
    public ResponseResult deleteOrder(@PathVariable Long orderId) {
        //删除订单
        if (!easyBuyOrderService.deleteOrder(orderId)) {
            return ResponseResult.error("删除订单失败");
        }
        return ResponseResult.success("删除订单成功");
    }

    //修改订单状态
    @PostMapping("/changeStatus")
    @CheckPermission({"0"})
    public ResponseResult changeStatus(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("orderId") || !params.containsKey("status")) {
            return ResponseResult.error("参数错误");
        }
        Long orderId = Long.parseLong(params.get("orderId").toString());
        Integer status = Integer.parseInt(params.get("status").toString());
        //修改订单状态
        if (!easyBuyOrderService.changeStatus(orderId, status)) {
            return ResponseResult.error("修改订单状态失败");
        }

        return ResponseResult.success("修改订单状态成功");
    }
}
